// pages/song/song.js
var appInstance = getApp();
import moment from "moment";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    songIndex: "",
    songId: "",
    author: "",
    songName: "",
    picUrl: "",
    songUrl: "",
    isPlay: false, //是否在播放
    SongsList: [],
    // 音乐进度条
    currentTime: "00:00",
    durationTime: "--:--",
    currentWidth: 0,
  },
  // 音乐播放进度条控制

  // 点击播放上/下一首歌
  changeSong(e) {
    const { id } = e.target;
    const songIndex = this.data.songIndex;
    const length = this.data.SongsList.length;
    // 上一首
    if (id === "pre") {
      if (songIndex === 0) {
        this.setData({ songIndex: length - 1 });
      }
      this.setData({ songIndex: this.data.songIndex * 1 - 1 });
      this.updataSongInfo();
      this.setData({ songUrl: "" });
    }
    // 下一首
    else {
      if (songIndex === length - 1) {
        this.setData({ songIndex: 0 });
      }
      this.setData({ songIndex: this.data.songIndex * 1 + 1 });
      this.updataSongInfo();
      this.setData({ songUrl: "" });
    }
    this.songPlayOrStop();
  },

  // 使用下标更新data中的歌曲相关信息，不包含URL
  updataSongInfo() {
    const songs = this.data.SongsList;
    const songIndex = this.data.songIndex;
    this.setData({
      songName: songs[songIndex].album.name,
      author: songs[songIndex].album.artists[0].name,
      picUrl: songs[songIndex].album.picUrl,
      songId: songs[songIndex].id,
      durationTime: moment(songs[songIndex].bMusic.playTime).format("mm:ss"),
    });
    wx.setNavigationBarTitle({
      title: this.data.songName,
    });
  },
  // 获取歌曲链接
  async getSongUrl() {
    // 请求歌曲链接
    const res = await wx.$request("/song/url", { id: this.data.songId });
    this.setData({
      songUrl: res.data[0].url,
    });
  },
  // 测试代码
  go() {
    // 播放进度跳到160秒处
    this.backgroundAudioManager.seek(160);
  },
  // 测试结束

  // 全局的歌曲状态监听
  addEvent() {
    this.backgroundAudioManager.onPlay(() => {
      // console.log('播放');
      this.setData({ isPlay: true });
    });
    this.backgroundAudioManager.onPause(() => {
      // console.log('暂停');
      this.setData({ isPlay: false });
    });
    this.backgroundAudioManager.onEnded(() => {
      // console.log('播放结束');
      // 顺序播放
      const songIndex = this.data.songIndex;
      const length = this.data.SongsList.length;
      if (songIndex === length - 1) {
        this.setData({ songIndex: 0 });
      }
      this.setData({ songIndex: this.data.songIndex * 1 + 1 });
      this.updataSongInfo();
      this.setData({ songUrl: "" });
      this.songPlayOrStop();
    });
    // 监听背景音频播放进度更新事件，只有小程序在前台时会回调
    this.backgroundAudioManager.onTimeUpdate(() => {
      this.setData({
        currentTime: moment(
          this.backgroundAudioManager.currentTime * 1000
        ).format("mm:ss"),
        currentWidth:
          (this.backgroundAudioManager.currentTime /
            this.backgroundAudioManager.duration) *100
          ,
      });
    });
  },
  // 播放与暂停，页面内按钮触发
  handlePlay() {
    this.setData({ isPlay: !this.data.isPlay });
    this.songPlayOrStop();
  },
  // 全局播放/暂停
  async songPlayOrStop() {
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    if (this.data.isPlay) {
      // 在没有songUrl才请求URL
      if (!this.data.songUrl) {
        await this.getSongUrl();
      }
      backgroundAudioManager.src = this.data.songUrl;
      backgroundAudioManager.title = this.data.songName;
      // 将状态缓存到实例上
      // 存储播放状态为播放
      appInstance.globalData.playState = true;
      // 缓存当前播放歌曲id
      appInstance.globalData.audioId = this.data.songId;
    } else {
      // 暂停
      backgroundAudioManager.pause();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // 要播放的歌曲下标
    this.setData({ songIndex: options.songIndex });
    // 获取传送到当前页面的数据
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on("getSongs", (SongsList) => {
      // 接收的数据存储到data中
      this.setData({ SongsList });
    });
    // 判断后台歌曲是否处于播放,歌曲是否与播放的一致
    const { audioId, playState } = appInstance.globalData;
    if (playState && audioId === this.data.songId) {
      this.setData({ isPlay: true });
    }
    this.backgroundAudioManager = wx.getBackgroundAudioManager();
    this.addEvent();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.updataSongInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
